//
//  SLPageTitleView.m
//  SLPageView
//
//  Created by 王胜利 on 2018/11/9.
//  Copyright © 2018 wsl. All rights reserved.
//  page标题（平分标题）
//

#define WEAK(type)   __weak typeof(type) weak##type = type;

////////////////////////////尺寸相关////////////////////////////
#define SCREEN_SIZE \
([[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)] ? CGSizeMake([UIScreen mainScreen].nativeBounds.size.width/[UIScreen mainScreen].nativeScale,[UIScreen mainScreen].nativeBounds.size.height/[UIScreen mainScreen].nativeScale) : [UIScreen mainScreen].bounds.size)



#import <Masonry/Masonry.h>
#import "SLPageTitleView.h"
#import "SLPageBaseScrollView.h"
#import "SLPageManager.h"
#import "SLBadgeButton.h"
//#import "ThemeKit.h"

@interface SLPageTitleView()

/// 滑动的线
@property (nonatomic, strong) UIView *scrollLine;
/// 按钮数组
@property (nonatomic, strong) NSMutableArray <UIView *>* btns;

@end

@implementation SLPageTitleView

@synthesize pageEntitys = _pageEntitys;
@synthesize titleBtnSelect = _titleBtnSelect;
@synthesize currentIdx = _currentIdx;


- (instancetype)init{
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.lineColor = UIColor.darkGrayColor;
        self.titleNormalColor = UIColor.grayColor;
        self.titleSelectColor = UIColor.blackColor;
    }
    return self;
}

- (void)setPageEntitys:(NSArray<SLPageEntity *> *)pageEntitys{
    _pageEntitys = pageEntitys;
    [self setTitlesAndThemeColor];
}

- (void)setLineColor:(UIColor *)lineColor{
    _lineColor = lineColor;
    self.scrollLine.backgroundColor = lineColor;
}

- (void)setTitleNormalColor:(UIColor *)titleNormalColor{
    _titleNormalColor = titleNormalColor;
    [self resetTitleColor];
}

- (void)setTitleSelectColor:(UIColor *)titleSelectColor{
    _titleSelectColor = titleSelectColor;
    [self resetTitleColor];
}


/// MARK: - 重设标题颜色
- (void)resetTitleColor{
    for (UIButton *btn in self.btns) {
        UIColor *color = (btn.tag == self.currentIdx+100)?self.titleSelectColor:self.titleNormalColor;
        [btn setTitleColor:color forState:UIControlStateNormal];
    }
}

#pragma mark - 更新布局
- (void)layoutSubviews{
    /// 布局滑动的线
    [self layoutScrollLine];
    [super layoutSubviews];
}

#pragma mark 初始化标题和主题色
- (void)setTitlesAndThemeColor{
    /// 设置标题
    for (int i = 0 ; i < self.pageEntitys.count; i++) {
        SLPageEntity *pageEntity = self.pageEntitys[i];
        SLBadgeButton *button = [self createTitleButtnWithIndex:i];
        button.pageEntity = pageEntity;
        [self addSubview:button];
        [self.btns addObject:button];
    }

    [self.btns mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:0 leadSpacing:0 tailSpacing:0];
    [self.btns mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self);
    }];

    [self layoutScrollLine];
}

/// MARK: - 创建标题按钮
- (SLBadgeButton *)createTitleButtnWithIndex:(NSUInteger)idx{
    SLBadgeButton *button = [SLBadgeButton buttonWithType:UIButtonTypeCustom];
    button.tag = idx+100;
    UIColor *color = idx == 0? self.titleSelectColor:self.titleNormalColor;
    [button setTitleColor:color forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    [button addTarget:self action:@selector(titleBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    return button;
}

/// MARK: - 标题按钮点击事件
- (void)titleBtnAction:(UIButton *)btn{
    NSInteger i = btn.tag - 100;
    [self scrollToIndex:i animated:NO];
    self.titleBtnSelect(i);
}

/// MARK: - 修改badge未读消息数
- (void)titleBadge:(NSString *)badge idx:(NSInteger)idx{
    SLBadgeButton *btn = (SLBadgeButton *)self.btns[idx];
    btn.badge = badge;
}

/// MARK: - 是否显示标题栏红点
- (void)isShowRedPoint:(BOOL)isShow idx:(NSInteger)idx{
    SLBadgeButton *btn = (SLBadgeButton *)self.btns[idx];
    btn.isShowRedPoint = isShow;
}

#pragma mark 根据Idx设置顶部按钮的背景颜色和位置
- (void)scrollToIndex:(NSInteger)idx animated:(BOOL)animated{
    /// 如果下标相同，即不需要切换分页的时候直接返回
    if (self.currentIdx == idx) {
        return;
    }
    self.currentIdx = idx;

    [self layoutScrollLine];

    WEAK(self)
    [UIView animateWithDuration:0.2 animations:^{
        /// 2.设置选中按钮的颜色改变
        [weakself resetTitleColor];
        [weakself layoutIfNeeded];
    }];
}

#pragma mark - 布局滑动的线
- (void)layoutScrollLine{
    [self layoutIfNeeded];
    /// 标题宽
    CGFloat titleBtnX = [self.btns[self.currentIdx] frame].origin.x;
    CGFloat btnWidth = self.btns[self.currentIdx].bounds.size.width;
    CGFloat titleWidth = [self.pageEntitys[self.currentIdx].title boundingRectWithSize:CGSizeMake(SCREEN_WIDTH, 35) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil].size.width;

    if (titleWidth > btnWidth) {
        titleWidth = btnWidth;
    }

    CGFloat lineXOffset = titleBtnX +(btnWidth - titleWidth)/2;
    [self.scrollLine mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(titleWidth));
        make.left.equalTo(self).offset(lineXOffset);
    }];
}

#pragma mark - lazyload
- (UIView *)scrollLine{
    if (!_scrollLine) {
        _scrollLine = [UIView new];
        _scrollLine.backgroundColor = self.lineColor;
        [self addSubview:_scrollLine];
        [_scrollLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(@1.5);
            make.width.equalTo(@0);
            make.bottom.equalTo(self);
        }];
    }
    return _scrollLine;
}

- (NSMutableArray<UIView *> *)btns{
    if (!_btns) {
        _btns = [NSMutableArray array];
    }
    return _btns;
}

@end
